package com.tonicgb.service;

import com.tonicgb.api.admin.request.LoginRequest;
import com.tonicgb.api.admin.response.LoginResponse;
import com.tonicgb.model.Admins;
import com.tonicgb.shared.core.jwt.JWTToken;
import com.tonicgb.shared.common.enums.MessageCodeEnum;
import com.tonicgb.shared.exception.ApiException;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthorizationsService {

    @Autowired
    private AdminService adminService;

    @Autowired
    private JWTToken jwtToken;
    public LoginResponse login(LoginRequest loginRequest) throws Exception {

        Admins admins=new Admins();
        admins.setName(loginRequest.getName());
        admins=adminService.get(admins);
        if(admins==null) throw new ApiException(MessageCodeEnum.ADMIN_NULL);
          try {
              if (!BCrypt.checkpw(loginRequest.getPwd(), admins.getPwd()))
                  throw new ApiException(MessageCodeEnum.ADMIN_PASSWORD_EORROR);
          }catch (Exception e){
                throw new ApiException(MessageCodeEnum.ADMIN_PASSWORD_EORROR);
        }
        LoginResponse loginResponse=new LoginResponse();
        String token=jwtToken.crateToken(admins);
        loginResponse.setAdmins(admins);
        loginResponse.setToken(token);
        loginResponse.setExpiredTime(jwtToken.claim.get("exp").asDate());

        return loginResponse;
    }



}
